package com.blue.Impl.author;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.blue.common.constant.CommonConstant;
import com.blue.po.author.UserPO;
import com.blue.service.author.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.blue.mapper.author.DeptMapper;
import com.blue.po.author.DeptPO;
import com.blue.service.author.IDeptService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;


@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, DeptPO> implements IDeptService {

    @Autowired
    private IUserService userService;

    @Override
    public void treeData(List<DeptPO> deptPOList, Boolean flag) {
        LambdaQueryWrapper<DeptPO> queryWrapper = new LambdaQueryWrapper<>();
        if (flag) {
            queryWrapper.eq(DeptPO::getStatus, CommonConstant.NORMAL);
        }
        List<DeptPO> deptPOS = this.list(queryWrapper);
        deptPOList = deptPOList.stream().peek(item -> item.setChildren(getChildren(item, deptPOS)))
                .sorted((item1, item2) -> (item1.getSort() == null ? BigDecimal.ZERO : item1.getSort()).compareTo(item2.getSort() == null ? BigDecimal.ZERO : item2.getSort()))
                .toList();
    }

    private List<DeptPO> getChildren(DeptPO root, List<DeptPO> allDept) {
        return allDept.stream()
                .filter(item -> root.getDeptId().equals(item.getParentId()))
                .peek(item -> item.setChildren(CollectionUtils.isEmpty(getChildren(item, allDept)) ? null : getChildren(item, allDept)))
                .sorted((item1, item2) -> (item1.getSort() == null ? BigDecimal.ZERO : item1.getSort()).compareTo(item2.getSort() == null ? BigDecimal.ZERO : item2.getSort()))
                .toList();
    }

    @Override
    @Transactional
    public void delete(List<String> ids) {
        this.removeByIds(ids);
        userService.update(new LambdaUpdateWrapper<UserPO>()
                .set(UserPO::getDeptId, null)
                .in(UserPO::getDeptId, ids));
    }
}
